<template>
  <div>
    <Breadcrumb :style="{margin: '16px 0'}">
      <BreadcrumbItem>首页</BreadcrumbItem>
      <BreadcrumbItem to="/department">部门管理</BreadcrumbItem>
      <BreadcrumbItem>添加部门</BreadcrumbItem>
    </Breadcrumb>
    <Card>
      <div style="min-height: 600px">
        <Row>
          <Col span="18" offset="3">
            <div>
              <h4>部门名称</h4>
              <Input type="text" v-model="deptName" placeholder="请输入部门名称" style="margin-top:7px;" />
            </div>
            <Divider></Divider>
            <div style="font-size: 14px;margin-top: 25px;">
              <h4>上级部门</h4>
              <Tree :data="deptData" @on-select-change="checkChange" ></Tree>
            </div>
            <Divider></Divider>
            <div>
              <Button type="primary" size="large" @click="handleSubmitDept">提交</Button>
            </div>
          </Col>
        </Row>
      </div>
    </Card>
  </div>
</template>

<script>
import qs from 'qs'
export default {
  data() {
    return {
      deptName: '',
      pid: 0,
      plevel: '',
      deptData: []
    };
  },
  methods: {
    checkChange(n, m) {
      console.log(m)
      this.pid = m.id
      this.plevel = m.level
    },
    handleSubmitDept() {
      if (this.deptName == '') {
        this.$Message.error('部门名称不能为空！')
        return false
      }
      this.$axios.post('/bm/opera/dept/addDept', qs.stringify({
        deptName: this.deptName,
        pid: this.pid,
        pLevel: this.plevel
      })).then(res => {
        if (res.data.code == 200) {
          this.$Message.success('部门添加成功！')
          this.$router.replace('/department')
        } else {
          this.$Message.error(res.data.description)
        }
      }).catch(err => {
        this.$Message.error('网络错误，请稍后重试！')
      })
    }
  },
  mounted() {
    // console.log(formatTree(this.deptData1));
    // this.deptData = formatTree(this.deptData1);
    this.$axios.get('/bm/opera/dept/findAllDeptTree').then(res => {
      if (res.data.code == 200) {
        this.deptData = formatTree(res.data.detail)
      } else {
        this.$Message.error(res.data.description)
      }
    }).catch(err => {
      this.$Message.error('网络错误，请稍后重试！')
    })
  }
};
function formatTree(subdata) {
  let arr = [];
  subdata.forEach((item, index) => {
    let subarr = {};
    subarr = {
      title: item.deptName,
      id: item.id,
      userCount: item.userCount,
      pid: item.pid,
      level: item.level,
      leadName: item.leadName,
      leadId: item.leadId,
      expand: true
    };

    if (item.sonDeptList.length > 0) {
      subarr.children = formatTree(item.sonDeptList);
    }

    arr.push(subarr);
  });

  return arr;
}
</script>

<style scoped>
.ivu-tree >>> .ivu-tree-title {
  font-size: 14px;
}
</style>
